import fs from 'fs';
import path from 'path';
import less from 'less';

// 创建css目录
const cssDir = path.join(process.cwd(), 'src', 'css');
if (!fs.existsSync(cssDir)) {
  fs.mkdirSync(cssDir, { recursive: true });
}

// Less变量和混合定义
const lessVariables = `
  @ease-in-out: cubic-bezier(0.645, 0.045, 0.355, 1);
  @ease-out: cubic-bezier(0.215, 0.61, 0.355, 1);
  @ease-in: cubic-bezier(0.55, 0.055, 0.675, 0.19);
  
  @line-color: #e9e9e9;
  @shadow-color: rgba(0, 0, 0, 0.15);
  @bottom-bar-bg-color: #262626;
  @bottom-bar-line-color: #000;
  @template-bg-color: #001529;
  @template-bg-color-light: #ececec;
  @template-nav-bg-color: #001529;
  @template-text-color: #ccc;
  @template-text-title-color: #bcbcbc;
  @template-text-color-light: #fff;
  @template-footer-text-color: #999;
  @animate-duration: .45s;
  
  // Ant Design变量
  @primary-color: #1DA57A;
  @text-color: #333;
  
  .page-shadow() {
    box-shadow: 0 5px 8px @shadow-color;
  }
  
  .page-pro() {
    border-radius: 6px;
    border: 1px solid @line-color;
    transform: translateY(0);
    transition: transform .3s @ease-out, box-shadow .3s @ease-out;
    &:hover {
      .page-shadow();
      transform: translateY(-5px);
    }
  }
`;

// 读取并转换所有less文件
const lessDir = path.join(process.cwd(), 'src', 'less');
const files = fs.readdirSync(lessDir);

// 处理每个less文件
files.forEach(file => {
  if (file.endsWith('.less') && file !== 'antMotionStyle.less' && file !== 'custom.less' && file !== 'common.less') {
    const filePath = path.join(lessDir, file);
    const cssFileName = file.replace('.less', '.css');
    const cssFilePath = path.join(cssDir, cssFileName);
    
    const lessContent = fs.readFileSync(filePath, 'utf8');
    
    // 跳过空文件
    if (lessContent.trim() === '') {
      console.log(`Skipped empty file ${file}`);
      return;
    }
    
    // 将变量和混合定义添加到less内容前面
    const fullLessContent = lessVariables + '\n' + lessContent;
    
    // 编译为CSS
    less.render(fullLessContent, { compress: false })
      .then(output => {
        // 写入CSS文件
        fs.writeFileSync(cssFilePath, output.css);
        console.log(`Converted ${file} to ${cssFileName}`);
      })
      .catch(error => {
        console.error(`Error converting ${file}:`, error);
      });
  }
});

// 获取非空的less文件列表
const nonEmptyFiles = files.filter(file => {
  if (file.endsWith('.less') && file !== 'antMotionStyle.less' && file !== 'custom.less' && file !== 'common.less') {
    const filePath = path.join(lessDir, file);
    const lessContent = fs.readFileSync(filePath, 'utf8');
    return lessContent.trim() !== '';
  }
  return false;
});

// 创建antMotionStyle.css文件
const antMotionStyleContent = nonEmptyFiles
  .map(file => `@import './${file.replace('.less', '.css')}';`)
  .join('\n');

fs.writeFileSync(path.join(cssDir, 'antMotionStyle.css'), antMotionStyleContent);
console.log('Created antMotionStyle.css');